define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock){

    var sysPath =  getServer() + "/static/app/cdqh/qhstandardpenetration";

    var qhStandardPenetrationFormHtml = sysPath + "/views/qhStandardPenetrationForm.html";
	var getQhStandardPenetrationController = function(){
		return getServer() + "/qh/qhStandardPenetrations";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
		initReviewStatusSelect();
        initDrillCode()
		createQhStandardPenetrationGrid();
	};
    var initDrillCode = function () {
        var drillCode = window.sessionStorage.getItem("drillJumpId");
        if(drillCode && drillCode.length > 0){
            $("#drillCodeCondition").val(drillCode);
            window.sessionStorage.setItem("drillJumpId","");
        }
    };
    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
	var initReviewStatusSelect = function () {
		$.ajax({
			url: getQhStandardPenetrationController() + "/getValidDictItemsByDictCode/" + "reviewStatusSelect",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("reviewStatusSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};



	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createQhStandardPenetrationGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
	            $("#citySelect").val("");
	            $("#areaSelect").val("");
	            $("#town").val("");
				$("#projectNameCondition").val("");
				$("#drillCodeCondition").val("");
	            $("#reviewStatusSelect").val("");
			});
	};
	var createQhStandardPenetrationGrid= function() {
        $("#qhStandardPenetrationGrid").datagrid({
            url:getQhStandardPenetrationController() + "/queryQhStandardPenetrations",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            idField:'id',
            columns:[[
                {field:"ck",checkbox:true},
				{
					field:'projectName',
					title:'勘察工程名称',
					width:'9%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
								return '<a href="#" onclick="_editQhStandardPenetration(\'' + rowData.id + '\');"> '+rowData.projectName+' </a> '
					}
				},
				{
					field:'province',
					title:'省',
					width:'9%',
					align:'center',
				},
				{
					field:'city',
					title:'市',
					width:'9%',
					align:'center',
				},
				{
					field:'area',
					title:'区（县）',
					width:'9%',
					align:'center',
				},
				{
					field:'town',
					title:'乡镇',
					width:'9%',
					align:'center',
				},
				{
					field:'drillCode',
					title:'钻孔编号',
					width:'8%',
					align:'center',
				},
				{
					field:'serialNumber',
					title:'序号',
					width:'8%',
					align:'center',
				},
				{
					field:'geotechnicalType',
					title:'岩石类型',
					width:'8%',
					align:'center',
				},
				{
					field:'standardStartDepth',
					title:'标准贯入起始深度',
					width:'8%',
					sortable: true,
					align:'center',
				},
				{
					field:'standardEndDepth',
					title:'标准贯入结束深度',
					width:'8%',
					sortable: true,
					align:'center',
				},
				{
					field:'standardHammerNumber',
					title:'标准贯入锤击数',
					width:'8%',
					sortable: true,
					align:'center',
				},
				{
					field:'reviewStatus',
					title:'数据状态',
					width:'6%',
					align:'center',
					formatter: function (value) {
                        if (value == 0) {
                            return '未提交';
                        } else if (value == 1) {
                            return '已提交';
                        } else if (value == 2) {
                            return '审核通过';
                        } else if (value == 3) {
                            return '审核未通过';
                        }
                    }
				},
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addQhStandardPenetration();
                }
            },{
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteQhStandardPenetration();
                }
            },{
				iconCls: 'fa fa-upload',
				text: "导入",
				handler: function () {
					importForm();

				}
			},{
				iconCls: 'fa fa-download',
				text: "导出",
				handler: function () {
					exportForm();
				}
			},{
				iconCls: 'fa fa-share-square-o',
				text: "提交",
				handler: function () {
					submit();
				}
			}],
            queryParams:{
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                town: $("#town").val(),
				projectName: $("#projectNameCondition").val(),
				drillCode: $("#drillCodeCondition").val(),
                reviewStatus: $("#reviewStatusSelect").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
	var formValidator = function(){
		$("#qhStandardPenetrationForm").validate({
			rules : {
				projectName : {
					required : true,
				},
				drillCode : {
					required : true,
				},
				serialNumber : {
					required : true,
				},
				province : {
					required : true,
				},
				city : {
					required : true,
				},
				area : {
					required : true,
				},
				geotechnicalType : {
					required : true,
				},
				standardStartDepth : {
					required : true,
					number: true
				},
				standardEndDepth : {
					required : true,
					number: true
				},
				standardHammerNumber : {
					required : true,
					number: true
				},
				standardMeasuredValue : {
					required : true,
					number: true
				},
			},
			messages : {
				projectName : {
					required : "勘察工程名称不允许为空!",
				},
				drillCode : {
					required : "钻孔编号不允许为空!",
				},
				serialNumber : {
					required : "序号不允许为空!",
				},
				province : {
					required : "省不允许为空!",
				},
				city : {
					required : "市不允许为空!",
				},
				area : {
					required : "区（县）不允许为空!",
				},
				geotechnicalType : {
					required : "岩石类型不允许为空!",
				},
				standardStartDepth : {
					required : "标准贯入起始深度不允许为空!",
				},
				standardEndDepth : {
					required : "标准贯入结束深度不允许为空!",
				},
				standardHammerNumber : {
					required : "标准贯入锤击数不允许为空!",
				},
				standardMeasuredValue : {
					required : "标准贯入实验实测值不允许为空!",
				},
				
			}
		});
	};
	var getQhStandardPenetration = function(id){
		$.ajax({
			url: getQhStandardPenetrationController() + "/"+id,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				Tool.deserialize("qhStandardPenetrationForm", data);
			}
		});
	};
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
	var addQhStandardPenetration = function () {
		var slidebar = Util.slidebar({
			url: qhStandardPenetrationFormHtml,
			width: "900px",
			cache: false,
			close : true,
			afterLoad: function () {
				initcreateProvinceForm();
				formValidator();
				$("#saveBtn").on("click", function () {
					if($("#qhStandardPenetrationForm").valid()){
						var data = Tool.serialize("qhStandardPenetrationForm");
						$.ajax({
							url: getQhStandardPenetrationController() ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createQhStandardPenetrationGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editQhStandardPenetration = function(qhStandardPenetrationId) {
		var slidebar = Util.slidebar({
			url: qhStandardPenetrationFormHtml,
			width: "900px",
			cache: false,
			close : true,
			afterLoad: function () {
				formValidator();
				getQhStandardPenetration(qhStandardPenetrationId);
				$("#saveBtn").on("click", function () {
					if($("#qhStandardPenetrationForm").valid()){
						var data = Tool.serialize("qhStandardPenetrationForm");
						$.ajax({
							url: getQhStandardPenetrationController(),
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "put",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createQhStandardPenetrationGrid();
							}
						});
					}
				});
			}
		});
	};
	var deleteQhStandardPenetration = function() {
		var rows = $("#qhStandardPenetrationGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.id + ",";

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getQhStandardPenetrationController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createQhStandardPenetrationGrid();
				}
			});
		}, function() {
			return;
		});

	};
//导入
	var importForm = function () {

		$("#uploadModal").modal();
		$("#uploadModal").on("shown.bs.modal", function () {
			var url = getServer() + "/fw/brick/downMould";
			$("#downloadZwExcelTemplate").attr("href", url);
		});

		$('#uploadButton').off("click");
		$("#uploadButton").on("click", function () {
			var uploadinput = document.getElementById("uploadFile");
			if (uploadinput.value == "") {
				Util.alert("上传前请先选择文件!");
				return;
			}
			var formData = new FormData();
			formData.append("file", uploadinput.files[0]);
			$.ajax({
				url: getQhStandardPenetrationController() + "/importFile",
				data: formData,
				processData: false, //因为data值是FormData对象，不需要对数据做处理。
				contentType: false,
				type: "POST",
				success: function (data) {
					$('#uploadModal').modal('hide');
					uploadinput.value = null;
					Util.alert(data);
					createQhStandardPenetrationGrid()
				}
			});
		});
	};
	//导出
	var exportForm = function () {
        var rows = $("#qhStandardPenetrationGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要导出选中的表单?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";
            });
            ids = ids.substr(0, ids.length - 1);
            window.location.href = getQhStandardPenetrationController() + "/exportFile/" + ids;
        }, function () {
            return;
        });

		// window.location.href = getQhStandardPenetrationController() + "/exportFile";
	};
	//提交
	var submit = function () {
		var rows = $("#qhStandardPenetrationGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		if (rows.length >= 1) {
			for (var i = 0; i < rows.length; i++) {
				if (rows[i].reviewStatus != '0') {
					Util.alert("只有数据状态为未提交的才能提交!");
					return;
				}
			}
		}
		Util.confirm("是否要提交选中的表单?", function () {
			var ids = "";
			$.each(rows, function (i, row) {
				ids += row.id + ",";
			});
			ids = ids.substr(0, ids.length - 1);
			$.ajax({
				url: getQhStandardPenetrationController() + "/submit/"+ ids,
				contentType: "application/json",
				type: "POST",
				success: function (data) {
					createQhStandardPenetrationGrid();
				}
			});
		}, function () {
			return;
		});

	};
	return {
		init:init
	};
});
